
$(document).ready(function() {
    let currentPage = 1;
    let pageSize = 10;
    
    // 初始化举报列表
    function initReportList() {
        // 显示加载中状态
        $('#ruleTableBody').html('<tr><td colspan="9" class="text-center py-4">加载中...</td></tr>');
        
        // 获取筛选参数
        const params = getFilterParams();
        
        // 调用后端接口获取数据
        fetchCollectionList(params)
            .then(result => {
                renderRuleList(result.data.list);
                renderPagination(result.data.total, currentPage, pageSize);
            })
            .catch(error => {
                // console.error('加载数据失败:', error);
                $('#ruleTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
            });
    }
    /**
     * 渲染分页控件
     * @param {number} total - 总记录数
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页条数
     */
    function renderPagination(total, currentPage, pageSize) {
        const totalPages = Math.ceil(total / pageSize);
        const paginationContainer = $('#paginationContainer'); // 分页容器
        
        // 清空现有分页
        paginationContainer.empty();
        
        // 上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage - 1}" ${prevDisabled}>
                <i class="fa fa-angle-left"></i>
            </button>
        `);
        
        // 页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整显示范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
            paginationContainer.append(`
                <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        // 下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage + 1}" ${nextDisabled}>
                <i class="fa fa-angle-right"></i>
            </button>
        `);
        
        // 更新分页信息
        const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        const end = Math.min(currentPage * pageSize, total);
        $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
    }
    /**
     * 获取筛选参数
     */
    function getFilterParams() {
        return {
            page: currentPage,
            pageSize: pageSize,
            status: $('#statusFilter').val(),
            applyType: $('#applyTypeFilter').val(),
            sort: $('#sortFilter').val(),
            keyword: $('#keywordSearch').val().trim(),
        };
    }

    /**
     * 获取举报列表
     * @param {*} params 
     * @returns 
     * */
    async function fetchCollectionList(params) {
        try {
            // 构建查询字符串
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    queryParams.append(key, value);
                }
            });

            // 发起请求
            const response = await fetch(`/system/GetAuditRuleList?${queryParams.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    // 根据实际需求添加认证信息
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.status/1 != 200) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            showToast(error.message || '获取媒体内容列表失败');
        }
    }

    // 渲染规则列表
    function renderRuleList(rules) {
        const tableBody = $('#ruleTableBody');
        tableBody.empty();
        
        if (rules.length === 0) {
            tableBody.append(`
                <tr>
                    <td colspan="8" class="px-5 py-10 text-center text-neutral-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-file-text-o text-4xl mb-2"></i>
                            <p>暂无审核规则数据</p>
                        </div>
                    </td>
                </tr>
            `);
            return;
        }
        
        rules.forEach(rule => {
            const statusClass = rule.status/1 === 1 ? 'bg-success/10 text-success' : 'bg-neutral-100 text-neutral-500';
            const statusText = rule.status/1 === 1 ? '启用' : '禁用';
            const toggleStatusText = rule.status/1 === 1 ? '禁用' : '启用';
            const toggleIcon = rule.status/1 === 1 ? 'fa fa-ban' : 'fa fa-check';
            
            tableBody.append(`
                <tr>
                    <td class="px-5 py-4 whitespace-nowrap">${rule.rule_id}</td>
                    <td class="px-5 py-4">${rule.name}</td>
                    <td class="px-5 py-4 whitespace-nowrap">${rule.apply_type}</td>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">${rule.created_by}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${rule.created_at}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${rule.updated_at}</td>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <div class="flex space-x-2">
                            <button class="text-primary hover:text-primary/80 edit-rule" data-id="${rule.rule_id}" title="编辑">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button class="text-warning hover:text-warning/80 toggle-status" data-id="${rule.rule_id}" data-status="${rule.status}" title="${toggleStatusText}">
                                <i class="${toggleIcon}"></i>
                            </button>
                            <button class="text-danger hover:text-danger/80 delete-rule" data-id="${rule.rule_id}" data-name="${rule.name}" title="删除">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `);
        });
    }
    // 初始化操作按钮事件
    function initActionEvents() {

        // 分页按钮点击事件
        $(document).on('click', '.pagination-btn', function() {
            const page = parseInt($(this).data('page'));
            if (!isNaN(page) && page !== currentPage) {
                currentPage = page;
                initReportList()
            }
        });
    }
    // 初始渲染
    initReportList()
    initActionEvents()
    
    // 打开新增规则模态框
    $('#addRuleBtn').click(function() {
        $('#modalTitle').text('新增审核规则');
        $('#ruleForm')[0].reset();
        $('#ruleId').val('');
        // 生成随机业务ID示例
        $('#ruleBusinessId').val('RUL-' + Math.floor(1000 + Math.random() * 9000));
        $('input[name="status"][value="1"]').prop('checked', true);
        $('#ruleModal').removeClass('hidden').addClass('flex');
    });
    
    // 关闭模态框
    $('#cancelModalBtn').click(function() {
        $('#ruleModal').removeClass('flex').addClass('hidden');
    });
    /**
     * 获取规则通用方法
     * @returns {Promise}
     */
    async function getRule(id) {
        try {
            let url = '';

            url = '/system/GetAuditRuleDetail?ruleId='+id;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    /**
     * 删除规则
     * @param {string} params.ruleId - 规则业务ID
     * @returns {Promise<Object>} 操作结果
     */
    async function delRule(id) {
        try {
            let url = '';

            url = '/system/DeleteRule';
            const requestData = {
                ruleId: id
            };
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    /**
     * 禁用/启用规则
     * @returns {Promise}
     */
    async function ChangeRule(id,status) {
        try {
            let url = '';

            url = '/system/ChangeAuditRuleStatus';
            const requestData = {
                ruleId: id,
                status: status
            };
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 编辑规则
    $(document).on('click', '.edit-rule', function() {
        const id = $(this).data('id');
        const rule = getRule(id);
        // console.log(rule);
        rule.then(function(data) {
            $('#modalTitle').text('编辑审核规则');
            $('#ruleId').val(data.rule_id);
            $('#ruleBusinessId').val(data.rule_id);
            $('#ruleName').val(data.name);
            $('#ruleContent').val(data.content);
            $('#applyType').val(data.apply_type);
            $('input[name="status"][value="' + data.status + '"]').prop('checked', true);
            $('#ruleModal').removeClass('hidden').addClass('flex');
        });
    });
    
    // 保存规则
    $('#ruleForm').submit(async function(e) {
        e.preventDefault();
        
        const id = $('#ruleId').val();
        const rule_id = $('#ruleBusinessId').val();
        const _name = $('#ruleName').val();
        const _content = $('#ruleContent').val();
        const _apply_type = $('#applyType').val();
        const _status = $('input[name="status"]:checked').val() * 1;
        
       

        try {
            let requestData = { 
                rule_id: rule_id,
                name:_name,
                content:_content,
                apply_type:_apply_type,
                status:_status
            };
            let url = '/system/CreateAuditRule';
            if (id) {
                requestData.id = id;
                url = '/system/UpdateAuditRule';
            }
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }

            // 重新渲染列表
            initReportList();
            
            // 关闭模态框并显示提示
            $('#ruleModal').removeClass('flex').addClass('hidden');
            showToast(id ? '规则更新成功' : '规则创建成功', 'success');
        }catch (error) {
            throw error; // 抛出错误给调用方处理
        }
        
        
    });
    
    // 显示删除确认
    $(document).on('click', '.delete-rule', function() {
        const id = $(this).data('id');
        $('#deleteRuleId').val(id);
        $('#deleteConfirmModal').removeClass('hidden').addClass('flex');
    });
    
    // 取消删除
    $('#cancelDeleteBtn').click(function() {
        $('#deleteConfirmModal').removeClass('flex').addClass('hidden');
    });
    
    // 确认删除
    $('#confirmDeleteBtn').click(function() {
        const id = $('#deleteRuleId').val();
        
        delRule(id).then(function(data) {
            showToast('规则已删除', 'success');
            initReportList()
        }).catch(function(error) {
            showToast(error.message, 'error');
        });
        
        $('#deleteConfirmModal').removeClass('flex').addClass('hidden');
    });
    
    // 切换规则状态
    $(document).on('click', '.toggle-status', function() {
        const id = $(this).data('id');
        const currentStatus = $(this).data('status');
        ChangeRule(id,currentStatus == 1 ? 0 : 1).then(function(data) {
            showToast('规则状态已更新', 'success');
            initReportList()
        });
    });
    
    // 筛选功能
    $('#applyTypeFilter, #statusFilter').change(function() {
        filterRules();
    });
    
    $('#keywordSearch').on('input', function() {
        filterRules();
    });
    
    // 筛选规则
    function filterRules() {
        const applyType = $('#applyTypeFilter').val();
        const status = $('#statusFilter').val();
        const keyword = $('#keywordSearch').val().toLowerCase();
        
        const filtered = ruleData.filter(rule => {
            // 适用类型筛选
            if (applyType && rule.apply_type !== applyType) return false;
            
            // 状态筛选
            if (status !== '' && rule.status !== status * 1) return false;
            
            // 关键词筛选
            if (keyword && !(rule.name.toLowerCase().includes(keyword) || rule.rule_id.toLowerCase().includes(keyword))) {
                return false;
            }
            
            return true;
        });
        
        renderRuleList(filtered);
    }
    
    // 复用layout.html中的toast提示函数
    function getToastIcon(type) {
        switch(type) {
            case 'success': return 'fa-check-circle';
            case 'error': return 'fa-times-circle';
            case 'warning': return 'fa-exclamation-triangle';
            case 'info': return 'fa-info-circle';
            default: return 'fa-info-circle';
        }
    }
    
    function showToast(message, type = 'info', duration = 3000) {
        // 移除已存在的toast
        $('.toast').remove();
        
        // 创建toast元素
        const toast = $(`
            <div class="toast toast-top-center toast-hidden toast-${type}">
                <i class="fa toast-icon ${getToastIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `);
        
        // 添加到页面
        $('body').append(toast);
        
        // 显示toast
        setTimeout(() => {
            toast.removeClass('toast-hidden');
        }, 10);
        
        // 自动隐藏
        setTimeout(() => {
            toast.addClass('toast-hidden');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, duration);
    }
});